package com.westos.dao;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.westos.domain.User;
import com.westos.utils.MD5Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;


import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

/**
 * @Author: ShenMouMou
 * @CreateTime: 2019-12-27 10:20
 * @Company:西部开源教育科技有限公司
 * @Description:爱生活，爱Java!
 */
public class UserDao {
    private  DataSource dataSource;

    public DataSource getDataSource() throws Exception {
        if(dataSource==null){
            createDataSource();
        }
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void createDataSource() throws Exception {
        Properties properties = new Properties();
        InputStream in = UserDao.class.getClassLoader().getResourceAsStream("druid.properties");
        properties.load(in);
        dataSource = new DruidDataSourceFactory().createDataSource(properties);

    }

    public boolean findUsername(String username) throws Exception {
        getDataSource();
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        PreparedStatement preparedStatement = connection.prepareStatement("select * from user where username=?");
        preparedStatement.setString(1, username);
        ResultSet resultSet = preparedStatement.executeQuery();
        boolean b = !resultSet.next();
        return b;
    }

    public void registerUser(User user) throws Exception {
        getDataSource();
        QueryRunner queryRunner = new QueryRunner(dataSource);
        queryRunner.update("insert into user values(?,?,?)", user.getUid(), user.getUsername(), MD5Utils.getMD5(user.getPassword()));

    }

    public User login(User user) throws Exception {
        getDataSource();
        QueryRunner queryRunner = new QueryRunner(dataSource);
        User user1 = queryRunner.query("select * from user where username=? and password=?", new BeanHandler<User>(User.class), user.getUsername(), MD5Utils.getMD5(user.getPassword()));

        return user1;
    }
}
